package com.ce.source.analysis.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ：前世小和尚（xiaopingzhang8@creditease.cn）
 * @Description ：Lock锁分析
 * @ClassName ：LockAnalyse
 * @Company ：普信恒业科技发展（北京）有限公司
 * @date ：2018/4/3 15:42
 */
public class LockAnalyse {

    public static void main(String[] args) throws Exception {
        final ReentrantLock lock = new ReentrantLock();
        lock.lockInterruptibly();

        lock.unlock();
        new Thread("thread-1") {
            public void run() {
                try {
                    if (lock.tryLock()) {
                        System.out.println(Thread.currentThread().getName() + " 获得锁");
                        System.out.println(Thread.currentThread().getName() + " 处理中……");
                    }
//                    TimeUnit.SECONDS.sleep(100000);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }.start();

        new Thread("thread-2") {
            public void run() {
                try {
                    if (lock.tryLock()) {
                        System.out.println(Thread.currentThread().getName() + " 获得锁");
                        System.out.println(Thread.currentThread().getName() + " 处理中……");
//                        TimeUnit.SECONDS.sleep(100000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        }.start();


        System.in.read();
    }
}
